package com.sam.learn.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sam.learn.entity.MailEntity;
import com.sam.learn.mapper.MailMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Random;

/**
 * @classname: MailSenderConfig
 * @description: TODO
 * @Author: sam
 * @date: 2022/10/23 22:27
 */
@Slf4j
@Component
@AllArgsConstructor
public class MailSenderConfig {
    private final List<JavaMailSenderImpl> senderList;

    private final MailMapper mailMapper;

    private final MailProperties mailProperties;
    /**
     * 获取MailSender
     * @return
     */
    public JavaMailSenderImpl getSender(){
        log.info("加载mail配置");
        if (senderList.isEmpty()) {
            buildMailSender();
        }
        // 随机返回一个
        return senderList.get(new Random().nextInt(senderList.size()));
    }

    /**
     * 清理 sender
     */
    public void clear() {
        senderList.clear();
    }

    @PostConstruct
    public void buildMailSender(){
        log.info("初始化mailSender");
        List<MailEntity> mails = mailMapper.selectList(new QueryWrapper<MailEntity>().eq("state", 1));
        /**
         * 需求：原本就是打算做成一个动态的邮件发送人，因为如果总是用一个邮件发送验证码或者是那种打扰短信，速度一旦太过于频繁，就会造成邮件发送错误。
         * 思路：从数据库中拿到所有可用的邮件发送人，然后封装起来，之后发送邮件时，再进行随机的选择即可。
         * 另外一种方式就是这是动态的。
         * 最后就是加个兜底的，如果数据库中查询不到邮件发送人，我们使用配置文件中的发送邮件的配置。
         */

        if (!mails.isEmpty()){
            mails.forEach(mail -> {
                JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
                javaMailSender.setDefaultEncoding(mail.getDefaultEncoding());
                javaMailSender.setHost(mail.getHost());
                javaMailSender.setPort(mail.getPort());
                javaMailSender.setProtocol(mail.getProtocol());
                javaMailSender.setUsername(mail.getUsername());
                javaMailSender.setPassword(mail.getPassword());
                // 添加数据
                senderList.add(javaMailSender);
            });
        }else {
            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
            javaMailSender.setDefaultEncoding(mailProperties.getDefaultEncoding());
            javaMailSender.setHost(mailProperties.getHost());
            javaMailSender.setPort(mailProperties.getPort());
            javaMailSender.setProtocol(mailProperties.getProtocol());
            javaMailSender.setUsername(mailProperties.getUsername());
            javaMailSender.setPassword(mailProperties.getPassword());
            // 添加数据
            senderList.add(javaMailSender);
        }
    }
}
